package com.cn.web.controller.mc;

import com.alibaba.fastjson2.JSONObject;
import com.cn.bean.dto.TestDto;
import com.cn.bean.pojo.bc.Assist;
import com.cn.bean.pojo.file.FileDetails;
import com.cn.bean.pojo.file.FileSizeFormatter;
import com.cn.config.config.Result;
import com.cn.service.server.admin.FileService;
import com.cn.service.server.mc.TestService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@CrossOrigin
@RestController
public class TestController {
    @Autowired
    private TestService testService;
    @Autowired
    private FileService fileService;
    private final String uploadDir = "D:\\上传文件";

    @RequestMapping("/select/test")
    @ResponseBody
    public List<TestDto> selectTest(@RequestBody TestDto testDto) {
        List<TestDto> assists = testService.selectTest(testDto);
        return assists;
    }
    @RequestMapping("/select/test2")
    @ResponseBody
    public List<TestDto> selectTest2(@RequestBody TestDto testDto) {
        List<TestDto> assists = testService.selectTest2(testDto);
        return assists;
    }
    @RequestMapping("/insert/test")
    @ResponseBody
    public Result addTest(@RequestBody TestDto testDto) {
        int test = testService.addTest(testDto);
        if (test==1){
            return Result.success("200","添加成功");
        }
        return Result.failure("500","操作失败");
    }
    @RequestMapping("/update/test")
    @ResponseBody
    public Result updateTest(@RequestBody TestDto testDto) {
       int test = testService.updateTest(testDto);
       if (test==1){
           return Result.success("200","操作成功");
       }
        return Result.failure("500","操作失败");
    }
    @RequestMapping("/update/zt")
    @ResponseBody
    public Result updateZT(@RequestBody TestDto testDto) {
        int test = testService.updateZT(testDto);
        if (test==1){
            return Result.success("200","操作成功");
        }
        return Result.failure("500","操作失败");
    }
    @RequestMapping("/del/test")
    @ResponseBody
    public Result delTest(@RequestBody TestDto testDto) {
      int test = testService.delTest(testDto);
      if (test==1){
          return Result.success("200","删除成功");
      }
        return Result.failure("500","操作失败");
    }
    //文件查询
    @RequestMapping("/select/upload")
    @ResponseBody
    public List<FileDetails> selectUpload(@RequestBody FileDetails fileDetails) {
        List<FileDetails> assists = fileService.selectUpload(fileDetails);
        return assists;
    }
    @RequestMapping("/download")
    @ResponseBody
    public ResponseEntity<Resource> downloadFile(@RequestBody FileDetails fileDetails) throws IOException {
        String filePath=fileDetails.getFilePath();
        filePath=filePath.trim();
        Path file = Paths.get(filePath);
        Resource resource = new UrlResource(file.toUri());

        if (resource.exists() && resource.isReadable()) {
            HttpHeaders headers = new HttpHeaders();
            String encodedFileName = UriUtils.encode(fileDetails.getFileName(), StandardCharsets.UTF_8);
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + encodedFileName);

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    //文件删除
    @RequestMapping("/del/upload")
    @ResponseBody
    public Result delUpload(@RequestBody FileDetails fileDetails) {
        try {
            String filePath = fileDetails.getFilePath();
            int id=fileDetails.getId();
            File file = new File(filePath);
            if (file.exists()) {
                if (file.delete()) {
                   int result=fileService.delScxx(id);
                   if (result==1){
                       return Result.success("200", "文件删除成功");
                   }
                    return Result.failure("500", "文件删除失败");
                } else {
                    return Result.failure("500", "文件删除失败");
                }
            } else {
                return Result.failure("404", "文件不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failure("500", "文件删除失败，服务器内部错误");
        }
    }
    //文件上传
    @RequestMapping("/upload")
    @ResponseBody
    public Result handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.failure("502","上传文件不能为空");
        }
        try {
            // 创建上传目录
            File directory = new File(uploadDir);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            // 保存文件
            String fileName = file.getOriginalFilename();
            String filePath = uploadDir + File.separator + fileName;
            file.transferTo(new File(filePath));

            // 构造响应
            String fileType = file.getContentType();
            long fileSize = file.getSize();
            String formattedFileSize = FileSizeFormatter.formatSize(fileSize);
            String uploadTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            String uploader = "后端处理"; // 这里可以根据实际情况获取上传人信息

            String response = "文件类型: " + fileType + "\n" +
                    "文件名称: " + fileName + "\n" +
                    "文件路径："+filePath+"\n"+
                    "文件大小: " + formattedFileSize + " \n" +
                    "上传时间: " + uploadTime + "\n" +
                    "上传人: " + uploader;

            FileDetails fileDetails = new FileDetails();
            fileDetails.setFileName(fileName);
            fileDetails.setFilePath(filePath);
            fileDetails.setFileType(fileType);
            fileDetails.setFileSize(fileSize);
            fileDetails.setFormattedFileSize(formattedFileSize);
            fileDetails.setUploadDir(uploadDir);
            fileDetails.setUploadTime(uploadTime);
            fileDetails.setUploader(uploader);
            List<FileDetails>cf=fileService.selectCf(fileName);
            if (cf.size()==0){
                int result = fileService.uploadFile(fileDetails);
                if (result > 0) {
                    return Result.success("200",response);
                } else {
                    return Result.failure("500", "文件上传失败");
                }
            }
            return Result.failure("501","不可以上传重复的文件！");
            // 保存文件信息到数据库
        } catch (IOException e) {
            e.printStackTrace();
            return Result.failure("500","上传文件失败: " + e.getMessage());
        }

    }

}
